package com.lanou3g.code0416;

import java.io.*;

/**
 * Created by dllo on 18/4/16.
 */
public class Test03 {
    public static void main(String[] args) {
        read();
        write();


    }

    public static void write(){

        File file = new File("text.txt");
        // BufferedWriter( 只能写String) 还是不方便,写文本的时候,通常使用PrintWriter
        PrintWriter pw = null;
        OutputStreamWriter  osw = null;
        FileOutputStream fos = null;


        try {

            pw  = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file)));
            //是否是追加模式,根据FileOutPutStream来走,再加一个true参数,就是追加模式

            fos = new FileOutputStream(file,true);  // 字节流
            osw = new OutputStreamWriter(fos);  //字符流
            pw = new PrintWriter(osw);

            //写入文件的时候,用法根System.out一样
            pw.println(1);
            pw.println("jsdkjfsd f");
            pw.println("窗前迷你个月给");
            pw.print("惊了刺秦王");
            pw.print("哈哈哈😆哈哈哈哈");
            //全部写完之后,务必加上flush,养成好习惯    读流不加写流加flush
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeAll(pw);
        }
    }


    //使用字符流读取文本信息
    public static void read(){

        File file = new File("text.txt");
        BufferedReader reader = null;
        InputStreamReader isr = null;
        FileInputStream fis = null;

        try {
           // reader  = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
           // isr.read(); // 读的是字符数组
            reader = new BufferedReader(isr);

            String line = "";
            StringBuilder sb = new StringBuilder();

            while ((line = reader.readLine())!=null){  //readLine() 读一行
                //  如果最后的结果,想要保留换行信息,则需要手动拼接换行,大多数情况下,都不需要
                //while循环中对 读到的每行数据进行各种操作
                sb.append(line).append("\n");

                System.out.println("->"+line);
            }
            String result = sb.toString();
            System.out.println(result);


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeAll(reader);
        }


    }


}
